package com.waitingsnow.common.share
{
    import com.waitingsnow.common.share.sinaMicroblog.API;
    import com.waitingsnow.common.share.sinaMicroblog.MicroBlog;
    import com.waitingsnow.common.share.config.AppInfo;
    import com.waitingsnow.common.share.events.ShareEvent;
    import com.waitingsnow.common.share.util.DataUtils;
    import com.waitingsnow.core.debug.Logger;
    
    import flash.events.Event;
    import flash.events.LocationChangeEvent;
    import flash.media.StageWebView;
    import flash.net.URLVariables;
    import flash.utils.ByteArray;
    
    /**
     * 新浪分享 
     * @author NeilWang
     * 
     */
    public class ShareToSina extends BaseShare
    {
        //==========================================================================
        //  Class variables
        //==========================================================================
        
        //==========================================================================
        //  Constructor
        //==========================================================================
        /**
         * Constructs a new <code>ShareToSina</code> instance.
         * 
         */
        public function ShareToSina()
        {
            super();
            
            addEventListener(Event.ADDED_TO_STAGE, init);
            init();
        }
        //==========================================================================
        //  Properties
        //==========================================================================
        private var blog:MicroBlog;
        
        //==========================================================================
        //  Methods
        //==========================================================================
        /**
         * 初始化 
         * @param parames
         * 
         */    
        private function init(...parames):void
        {
            blog = new MicroBlog();
            blog.consumerKey = AppInfo.SINA_APP_KEY;
            blog.consumerSecret = AppInfo.SINA_APP_SECRET;
            checkToken();
        }
        
        /**
         * 分享
         *
         */
        override public function share(message:String = "", pic:ByteArray=null):void
        {
            blog.updateStatus(message, pic);
        }
        
        /**
         * 先从缓存中获取应用ID和应用密钥
         */		
        override public function checkToken():void
        {
            //判断是否已经授权
            if(blog.access_token)
            {
                //已经被授权，直接获取数据
            }
            else
            {
                //开始获取授权
                startAuth();
            }
        }   
        
        /**
         * 授权
         * 
         */    
        private function startAuth():void
        {
            getAccessToken();
        }
        
        /**
         * 获取accessToken 
         * 
         */    
        private function getAccessToken():void
        {
            var authorURL:String = API.OAUTH_AUTHORIZE_REQUEST_URL + "?client_id=" + AppInfo.SINA_APP_KEY;
            authorURL += "&state=" + AppInfo.SINA_APP_KEY + Math.round(Math.random() * 1000000);
            authorURL += "&display=flash";	
            authorURL += "&response_type=token";
            webView = new StageWebView();
            webView.stage = stage;
            webView.viewPort = area;
            webView.loadURL(encodeURI(authorURL));
            webView.addEventListener(Event.COMPLETE, webViewCompleteHandler);
            webView.addEventListener(LocationChangeEvent.LOCATION_CHANGE, 
                webViewChangeHandler);
        }
        
        
        /**
         * 从地址上获取accessToken
         * @param url
         * 
         */    
        private function checkBackUrl(url:String):void
        {
            if (blog.access_token)
            {
                return;
            }
            Logger.debug(url);
            var urlVar:URLVariables = DataUtils.getURLVariables(url);
            if (urlVar.access_token)
            {
                blog.access_token = urlVar.access_token;
                blog.expires_in = urlVar.expires_in;
                webView.dispose();
                webView = null;
                dispatchEvent(new ShareEvent(ShareEvent.AUTHORIZE_COMPLETE));
				Logger.debug("成功登录新浪微博");
            }
            
        }
        //==========================================================================
        //  Event Handlers
        //==========================================================================
        private function webViewChangeHandler(event:LocationChangeEvent):void
        {
            checkBackUrl(webView.location);
        }
        
        private function webViewCompleteHandler(event:Event):void
        {
            checkBackUrl(webView.location);
        }
        
    }
}